<?php
class EventsController extends AppController {

	var $name = 'Events';
        var $paginate = array(
            'order' => array('Event.event_start' => 'asc')
        );

        var $uses = array('Event','User','Rsvp');

        var $helpers = array('Html', 'Form', 'Javascript');

        var $components = array('Acl');

	function index($event_type = null,$event_time = null) {





            $type = $this->Session->read('account_type');

            $this->set('type', $type);

            if(!$event_time){
                $this->set('event_time', 'upcoming');
            } else {
                $this->set('event_time', $event_time);
            }


            if($event_type){
                $this->set('ev_type',$event_type);
            }else{
                $this->set('ev_type','');
            }

            $date = date('Y-m-d H:i:s');

            if ($type == 'user'){

                $user = $this->Session->read('user');
                $user_id = $user['id'];

                $this->set('id_user', $user_id);

                $this->Event->recursive = 0;
         
                if ($event_type == 'invites'){

                    if (!$event_time) {

                        $this->set('events'
                                , $this->paginate($this->Event->Invite
                                        , array('Event.event_start > "'.$date.'"','Invite.user_id'=>$user_id)));
                    }else if($event_time == 'upcoming'){

                        $this->set('events'
                                , $this->paginate($this->Event->Invite
                                        , array('Event.event_start > "'.$date.'"','Invite.user_id'=>$user_id)));
                    } else if($event_time == 'past'){
                        $this->set('events'
                                , $this->paginate($this->Event->Invite
                                        , array('Event.event_start < "'.$date.'"','Invite.user_id'=>$user_id)));
                    }
                    
                }
                elseif($event_type == 'rsvps'){

                    if (!$event_time) {
                        $this->set('events'
                                , $this->paginate($this->Event->Rsvp
                                        , array('Event.event_start > "'.$date.'"','Rsvp.user_id'=>$user_id)));
                    }else if($event_time == 'upcoming'){
                        $this->set('events'
                                , $this->paginate($this->Event->Rsvp
                                        , array('Event.event_start > "'.$date.'"','Rsvp.user_id'=>$user_id)));
                    } else if($event_time == 'past'){
                        $this->set('events'
                                , $this->paginate($this->Event->Rsvp
                                        , array('Event.event_start < "'.$date.'"','Rsvp.user_id'=>$user_id)));
                    }
                    

                }else{//local events -- default

                    if (!$event_time) {
                        $this->set('events'
                                , $this->paginate($this->Event
                                        , array('Event.event_type'=>'public','Event.event_start > "'.$date.'"')));
                    }else if($event_time == 'upcoming'){
                        
                        $this->set('events'
                                , $this->paginate($this->Event
                                        , array('Event.event_type'=>'public','Event.event_start > "'.$date.'"')));
                    } else if($event_time == 'past'){
                    
                        $this->set('events'
                                , $this->paginate($this->Event
                                        , array('Event.event_type'=>'public','Event.event_start < "'.$date.'"')));
                    }
                    
                }

            }else{
                //This is host side
                
                $host = $this->Session->read('host');
                $this->Event->recursive = 0;
                $host_id = $host['id'];
                $this->set('host_i', $host_id);
                if (!$event_time) {
                  

                    $this->set('events'
                            , $this->paginate($this->Event->EventHost
                                    , array('Event.event_start > "'.$date.'"'
                                        , 'EventHost.host_id'=>$host_id)));
                } else if($event_time == 'upcoming'){
                   
                    $this->set('events'
                            , $this->paginate($this->Event->EventHost
                                    , array('Event.event_start > "'.$date.'"'
                                        , 'EventHost.host_id'=>$host_id)));
                } else if($event_time == 'past'){
                   
                    $this->set('events'
                            , $this->paginate($this->Event->EventHost
                                , array('Event.event_start < "'.$date.'"'
                                        , 'EventHost.host_id'=>$host_id)));
                }
            }
            
	}

	function view($event_type = null, $id = null) {
            
		if (!$id) {
			$this->Session->setFlash(__('Invalid event', true));
			$this->redirect(array('action' => 'index'));
		}
		  $u= $this->Session->read('account_type');
                if ($u== 'host')
                {
                    $biz= $this->Session->read('host');
                    $biz_id= $biz['business_name'];
                    $this->set('biz', $biz_id);
                }//This above code is here to help locate the
                //busiensses name and pass it along to the view function
                //So that it can be seen in the view event co-hosts page.
                $event_aux = $this->Event->read(null, $id);
                
                $type = $this->Session->read('account_type');

                //Checking if this host/user can view this event
                if ($type == 'user'){

                    $user = $this->Session->read('user');
                    $alias = $id.'-'.$event_aux['Event']['event_name'];

                    if (!$this->Acl->check($user['email_addr'],$alias, 'read')) {

                        $this->Session->setFlash(__('You cannot view this event.', true));
                        $this->redirect(array('action' => 'index',$event_type));

                    }

                }else{

                    $host = $this->Session->read('host');
                    $alias = $id.'-'.$event_aux['Event']['event_name'];

                    if (!$this->Acl->check($host['email_addr'],$alias, 'read')) {

                        $this->Session->setFlash(__('You cannot view this event.', true));
                        $this->redirect(array('action' => 'index',$event_type));

                    }
                     $this->set('temp', $this->Event->query("Select
                        EventHost.id,Host.business_name, EventHost.host_type
                        from Events as Event, Event_Hosts as EventHost, Hosts as Host where
                                Host.id = EventHost.host_id and
                                Event.id = EventHost.event_id and                                
                                Event.id = $id"));

                }

                $this->set('event', $this->Event->read(null, $id));

                $this->set('ev_type',$event_type);
                $this->set('type', $type);

                //looking for remaining capacity and number of guests attending
                $rsvp = $this->Event->Rsvp->find('first',
                        array('fields' =>
                            array('COUNT(*)+sum(num_of_guests)as registered'),
                            'conditions' => array('Rsvp.event_id'=>$id,
                                'OR'=>array(
                                    array('Rsvp.rsvp_status'=>'M'),
                                    array('Rsvp.rsvp_status'=>'Y'))
                                )
                            )
                        );

                if ($rsvp[0]['registered']){
                    $register_nums = $rsvp[0]['registered'];
                }else{
                    $register_nums = 0;
                }
                

                $this->set('remaining_capacity', $event_aux['Event']['capacity'] - $register_nums);
                $this->set('attending', $register_nums);

                if ($type == 'user'){

                    $user_id = $user['id'];

                    $this->set('id_user', $user_id);

                    $this->set('first_name', $user['first_name']);

                    $this->set('last_name', $user['last_name']);

                    $this->set('id_event', $id);

                    $rsvp = $this->Event->Rsvp->find('first',array('conditions'=> array('user_id'=>$user_id,'event_id'=>$id)));

                    $this->set('attendance', $rsvp['Rsvp']['rsvp_status']);
                    $this->set('n_guests', $rsvp['Rsvp']['num_of_guests']);

                    $date = date('Y-m-d H:i:s');


                    //Looking for a existent review of the user
                    if(($event_type == 'rsvps') && ($date > $event_aux['Event']['event_start'])){

                        $this->set('rsvp_id', $rsvp['Rsvp']['id']);

                        $n_reviews = $this->Event->Rsvp->Review->find('count',array('conditions'=> array('Rsvp.user_id'=>$user_id,'Rsvp.event_id'=>$id)));

                        if ($n_reviews > 0){

                            $review = $this->Event->Rsvp->Review->find('first',array('conditions'=> array('Rsvp.user_id'=>$user_id,'Rsvp.event_id'=>$id)));

                            $this->set('user_review', $review['Review']['comment']);
                            $this->set('user_rating', $review['Review']['rating']);
                            $this->set('review_date', $review['Review']['review_ts']);
                            $this->set('review_id', $review['Review']['id']);

                        }

                        //Looking for the total amount of reviews there are for the event
                        $reviews = $this->Event->Rsvp->Review->find('all',array('conditions'=> array('Rsvp.event_id'=>$id)));

                        $users = array();

                        foreach ($reviews as $review){
                            $users[] = $this->User->find('first',array('conditions'=> array('User.id'=>$review['Rsvp']['user_id'])));
                        }
                        
                        $this->set('reviews_list', $reviews);
                        $this->set('users_list', $users);

                    }
                }
                
	}

	function add() {

		if (!empty($this->data)) {
			$this->Event->create();
			if ($this->Event->save($this->data)) {

                                $host= $this->Session->read('host');

                                $eventhostData['EventHost']['event_id'] = $this->Event->getInsertID();
                                $eventhostData['EventHost']['host_id'] = $host['id'];
                                $eventhostData['EventHost']['host_type'] = 'p';

                                if($this->Event->EventHost->save($eventhostData)){
                                    $this->Session->setFlash(__('The event has been saved', true));

                                    //Moving and renaming the file uploaded
                                    if($this->data['Event']['image']){
                                        $target_path = 'img/event/'.$eventhostData['EventHost']['event_id'].'.jpg';
                                        move_uploaded_file($this->data['Event']['image']['tmp_name'], $target_path);
                                    }

                                    $alias = $this->Event->id.'-'.$this->data['Event']['event_name'];
                                    $parent = $this->Acl->Aco->findByAlias($host['email_addr']);

                                    //Creating ACO for new event
                                    $this->Acl->Aco->create(array(
                                        'alias' => $alias,
                                        'model' => 'Event',
                                        'foreign_key' => $eventhostData['EventHost']['event_id'],
                                        'parent_id' => $parent['Aco']['id'])
                                        );
                                    $this->Acl->Aco->save();

                                    /* Assigning permissions
                                     * Hosts that create the event can operate with it
                                     * All users or host can read them
                                     */
                                    $this->Acl->allow('Users', $alias, 'read');
                                    $this->Acl->allow('Hosts', $alias, 'read');
                                    $this->Acl->allow($host['email_addr'], $alias);
                                    
                                    $this->redirect(array('action' => 'index'));
                                    
                                }else{
                                    $this->Event->delete($this->Event->getInsertID());
                                    $this->Session->setFlash(__('The event could not be saved. Please, try again.', true));
                                }

                                
			} else {
				$this->Session->setFlash(__('The event could not be saved. Please, try again.', true));
			}
		}
	}

	function edit($id = null) {

            if (!$id && empty($this->data)) {
                $this->Session->setFlash(__('Invalid event', true));
                $this->redirect(array('action' => 'index'));
            }

            $event = $this->Event->read(null, $id);
            $host = $this->Session->read('host');

            $this->set('event', $event);

            $alias = $id . '-' . $event['Event']['event_name'];

            //Checking if this host can update this event
            if ($this->Acl->check($host['email_addr'], $alias, 'update')) {

                if (!empty($this->data)) {

                    if ($this->Event->save($this->data)) {
                        
                        $this->Session->setFlash(__('The event has been saved', true));

                        //If event name changes --> Updating ACO
                        if ($event['Event']['event_name'] != $this->data['Event']['event_name']) {

                            $aco = $this->Acl->Aco->findByAlias($alias);

                            $aco_id = $aco['Aco']['id'];

                            $alias = $id . '-' . $this->data['Event']['event_name'];

                            $query = 'update acos set alias = \'' . $alias . '\' where id = ' . $aco_id;

                            $this->Event->query($query);
                        }


                        //Moving and renaming the file uploaded
                        if ($this->data['Event']['image']) {
                            $target_path = 'img/event/' . $event['Event']['id'] . '.jpg';
                            move_uploaded_file($this->data['Event']['image']['tmp_name'], $target_path);
                        }

                        $this->redirect(array('action' => 'index'));
                    } else {
                        $this->Session->setFlash(__('The event could not be saved. Please, try again.', true));
                    }
                }

                if (empty($this->data)) {
                    $this->data = $this->Event->read(null, $id);
                }
            } else {
                $this->Session->setFlash(__('You are not the owner of this event. You cannot edit it.', true));
                $this->redirect(array('action' => 'index'));
            }
	}

	function delete($id = null) {
            
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for event', true));
			$this->redirect(array('action'=>'index'));
		}
                $host = $this->Session->read('host');
                $this->Event->recursive = 0;
                $host_id = $host['id'];

                $event = $this->Event->read(null, $id);
                $host = $this->Session->read('host');

                $alias = $id.'-'.$event['Event']['event_name'];

                //Checking if this host can delete this event
                if ($this->Acl->check($host['email_addr'],$alias, 'delete')) {
                    if($this->Event->query("CALL delete_event(".$id.")")){
                       
                            //Delete the related ACO
                            $aco = $this->Acl->Aco->findByAlias($alias);
                            $this->Acl->Aco->delete($aco['Aco']['id']);

                            $this->Session->setFlash(__('Event deleted', true));
                            $this->redirect(array('action'=>'index'));
                        
                    } else {
                         $this->Session->setFlash(__('Event was not deleted', true));
                         $this->redirect(array('action' => 'index'));
                    }
                   
                }else{

                    $this->Session->setFlash(__('You are not the owner of this event. You cannot delete it.', true));
                    $this->redirect(array('action' => 'index'));
                }
	}

        function report($id = null, $event_time = null) {
            
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for event', true));
			$this->redirect(array('action'=>'index'));
		}
            
                
            if(!$event_time){

                $this->set('event_time', 'upcoming');
            } else {
                $this->set('event_time', $event_time);
            }

                 $u= $this->Session->read('account_type');
                if ($u== 'host')
                {
                    $biz= $this->Session->read('host');
                    $biz_id= $biz['business_name'];
                    $this->set('biz', $biz_id);
                }//This above code is here to help locate the
                //busiensses name and pass it along to the report view
                //So that it can be seen in report on events page.
                $this->set('event', $this->Event->read(null, $id));
                $event_aux = $this->Event->read(null, $id);
                
                $host = $this->Session->read('host');

                $alias = $id.'-'.$event_aux['Event']['event_name'];

                if ($this->Acl->check($host['email_addr'],$alias,'create')) {
                
                    //Looking for the total amount of reviews there are for the event
                    $reviews = $this->Event->Rsvp->Review->find('all',array('conditions'=> array('Rsvp.event_id'=>$id)));

                    $users = array();

                    foreach ($reviews as $review){
                        $users[] = $this->User->find('first',array('conditions'=> array('User.id'=>$review['Rsvp']['user_id'])));
                    }

                    $this->set('reviews_list', $reviews);
                    $this->set('users_list', $users);

                    //looking for remaining capacity and number of guests attending/not attending/awaiting
                    $rsvp = $this->Event->Rsvp->find('first',array('fields' => array('COUNT(*)+sum(num_of_guests)as attending'),'conditions' => array('Rsvp.event_id'=>$id,'Rsvp.rsvp_status'=> 'Y')));

                    if ($rsvp[0]['attending']){
                        $register_nums = $rsvp[0]['attending'];
                    }else{
                        $register_nums = 0;
                    }

                    $rsvp = $this->Event->Rsvp->find('first',array('fields' => array('COUNT(*) as notattending'),'conditions' => array('Rsvp.event_id'=>$id,'Rsvp.rsvp_status'=>'N')));

                    if ($rsvp[0]['notattending']){
                        $not_attend = $rsvp[0]['notattending'];
                    }else{
                        $not_attend = 0;
                    }

                    $rsvp = $this->Event->Rsvp->find('first',array('fields' => array('COUNT(*)+sum(num_of_guests) as awaiting'),'conditions' => array('Rsvp.event_id'=>$id,'Rsvp.rsvp_status'=>'M')));

                    if ($rsvp[0]['awaiting']){
                        $await = $rsvp[0]['awaiting'];
                    }else{
                        $await = 0;
                    }

                    $this->set('remaining_capacity', $event_aux['Event']['capacity'] - ($register_nums+$await));
                    $this->set('attending', $register_nums);
                    $this->set('not_attending', $not_attend);
                    $this->set('awaiting', $await);


                }else{
                    $this->Session->setFlash(__('You are not the owner of this event. You cannot view event\'s reports.', true));
                    $this->redirect(array('action' => 'index'));
                }

	}

        
}
?>